package com.lw.edu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lw.commonutil.result.ResultCodeEnum;
import com.lw.edu.entity.Chapter;
import com.lw.edu.entity.Video;
import com.lw.edu.entity.chapter.ChapterVo;
import com.lw.edu.entity.chapter.VideoVo;
import com.lw.edu.mapper.ChapterMapper;
import com.lw.edu.service.ChapterService;
import com.lw.edu.service.VideoService;
import com.lw.servicebase.exception.GuliException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class ChapterServiceImpl extends ServiceImpl<ChapterMapper, Chapter> implements ChapterService {
    @Autowired
    private VideoService videoService;
    //课程大纲列表,根据课程id查询
    @Override
    public List<ChapterVo> getChapterVideoBycourseId(String courseId) {
        //查询出该课程下所有的章节
        List<Chapter> chapterList = baseMapper.selectList( new QueryWrapper<Chapter>().eq( "course_id", courseId ) );
        //查询出该课程下所有的小节
        List<Video> videoList = videoService.list( new QueryWrapper<Video>().eq( "course_id", courseId ) );
        //封装数据
        ArrayList<ChapterVo> chapterVos = new ArrayList<>();
        chapterList.stream().forEach( item->{
            //封装章节
            ChapterVo chapterVo = new ChapterVo();
            BeanUtils.copyProperties( item,chapterVo );
            chapterVos.add( chapterVo );
            //封装小节
            List<VideoVo> children= new ArrayList<>();
            videoList.stream().forEach( child -> {
                VideoVo videoVo = new VideoVo();
                //判断小节里的chapterId是否与章节id相等
                if (child.getChapterId().equals( item.getId() )){
                    BeanUtils.copyProperties( child,videoVo );
                    children.add( videoVo );
                }
            } );
            chapterVo.setChildren( children );
        } );
        return chapterVos;
    }

    //删除章节
    @Override
    public boolean deleteChapter(String chapterId) {
        //如果章节有小节，不让删除
        //根据chapterId查询小节
        QueryWrapper<Video> wrapper = new QueryWrapper<>();
        wrapper.eq( "chapter_id",chapterId );
        int count = videoService.count( wrapper );
        if (count>0){
            throw new GuliException( ResultCodeEnum.P_D );
        }
        //删除
        int i = baseMapper.deleteById( chapterId );
        return i>0;
    }
}
